"""Various helpful utility functions get dumped in here.
"""
from google.appengine.api import urlfetch
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db

import data

# Simple wrappers so we can do conversions without worrying about parse errors.
def SafeInt(numstring):
  try:
    return int(numstring)
  except ValueError:
    return 0

def SafeFloat(numstring, default=0.0):
  try:
    return float(numstring)
  except ValueError:
    return default

def PlayerCountInt(value):
  value = value.strip()
  if len(value) > 0 and value[0].isdigit():
    return int(value)
  # deal with this better
  # "more than X" etc.
  return 0


# Universal access to creating and deleting records for missing data.
def AddMissingRecord(bgguser):
  "Adds or updates record for missing user data"
  missing_query = data.MissingBGGUser.all()
  missing_query.filter("bgguser =", bgguser)
  res = missing_query.fetch(1)
  if not res:
    missing_record = data.MissingBGGUser()
    missing_record.bgguser = bgguser
    # This record didn't exist before. Set a flag for an automatic data update.
    web = urlfetch.fetch("http://www.rattus.net/cgi-bin/loadgame.cgi",
                         deadline=5, method=urlfetch.POST)
  else:
    missing_record = res[0]
  missing_record.put()

def ClearMissingRecord(bgguser):
  "Clears any records recording this user as missing"
  missing_query = data.MissingBGGUser.all()
  missing_query.filter("bgguser =", bgguser)
  res = missing_query.fetch(5)
  if res:
    db.delete(res)

# Secrets table. We really keep this in memcache.
def CheckToken(facility, token):
  "Checks whether a provided token for a facility matches our recorded one"
  secret_query = data.SecretEntry.all()
  secret_query.filter("facility =", facility)
  res = secret_query.fetch(1)
  if not res:
    return False
  secret = res[0]
  return secret.token == token
